package com.nitor.dns.validate;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.StringTokenizer;

public class CertDecrypt {
	
	public String recordToCert(String record){
		String result = null;
		BufferedInputStream bis = null;
		try{
			bis = new BufferedInputStream(new ByteArrayInputStream(getCert(record)));
			CertificateFactory cf;
			cf = CertificateFactory.getInstance("X.509");
			StringBuffer sb = new StringBuffer();
			while (bis.available() > 0) {
				X509Certificate certX509 = (X509Certificate) cf.generateCertificate(bis);
				String certX509_st = certX509.toString();
				if(certX509_st != null)
					sb.append(certX509_st);
			}
			result = sb.toString();
		}catch(Exception e){
			result = "Problem Loading Certificate: " + e;
		}finally{
			closeStreamQuietly(bis);
		}
		return result;
	}
	
	
	
	private byte[] getCert(String record) throws IOException{
		StringTokenizer st = new StringTokenizer(record);
		int i = 0;
		
		while(st.hasMoreTokens() && i < 3){
			st.nextToken();
			i++;
		}
		String cert = st.nextToken().toString();
		System.out.println("\n\nCERT: " + cert);
		return new sun.misc.BASE64Decoder().decodeBuffer(cert);
	}
	
	private void closeStreamQuietly(Closeable stream){
		try{
			if(stream != null)
				stream.close();
		}catch(IOException e){
			//do nothing for now (add logging functionality later)
		}
	}
	
	/**
	 * Test for decrypting cert.  Should be moved to JUnit test.
	 * @param args
	 */
	public static void main(String[] args){
		String cert = "1 124324 5 MIID2DCCAsCgAwIBAgIBBTALBgkqhkiG9w0BAQswfTEnMCUGA1UEAwweZGlyZWN0LWRhdmlkZGVncm9vdC11cyBSb290IENBMQswCQYDVQQIDAJEQzELMAkGA1UEBhMCVVMxEzARBgNVBAcMCldhc2hpbmd0b24xIzAhBgkqhkiG9w0BCQEWFGluZm9AZGF2aWRkZWdyb290LnVzMB4XDTEyMDUwNzE2NTcyOFoXDTEzMDUwNzE2NTcyOFowgY0xDzANBgNVBAMMBmR0czU1MDEOMAwGA1UECgwFTml0b3Ix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